package com.liaoyin.travel.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liaoyin.travel.base.entity.Page;
import com.liaoyin.travel.base.service.BaseService;
import com.liaoyin.travel.dao.DictBasicMapper;
import com.liaoyin.travel.entity.DictBasic;
import com.liaoyin.travel.entity.FileUpload;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.util.FileUploadUtil;
import com.liaoyin.travel.util.UUIDUtil;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DictBasicService extends BaseService<DictBasicMapper, DictBasic> {

	//用于缓存字典项小于150的字典内容
	private static Map<String, List<DictBasic>> dicts = new HashMap<>();


	//@Cacheable(value="selectDictBasic",key="selectDictBasic")
	public PageInfo<DictBasic> selectDictBasic(DictBasic dictBasic) {
		// 进行分页
		executePage(dictBasic);
		orderBy(dictBasic);
		return new PageInfo<DictBasic>(this.selectList(dictBasic));
	}


	//@Cacheable(value="selectDictBasicByPage",key="selectDictBasicByPage")
	public PageInfo<DictBasic> selectDictBasicByPage(String[] code, Page page) {
		executePage(page);
		orderBy(page);
		return new PageInfo<>(mapper.selectDictBasics(code));
	}


	//@Cacheable(value="selectDictBasics",key="selectDictBasics")
	public List<DictBasic> selectDictBasics(String[] strings) {
		return this.mapper.selectDictBasics(strings);
	}


	//@Cacheable(value="selectDictBasicsWithGroup",key="selectDictBasicsWithGroup")
	public List<DictBasic> selectDictBasicsWithGroup(String[] strings) {

		//参数只有1个查询的情况,从缓存里面取
		if (strings.length == 1) {
			List<DictBasic> result = new ArrayList<>();
			String[] args = strings[0].split(",");
			String code = args[0];
			result = this.selectDictByCode(code);
			if (args.length > 1) {
				String groupCode = args[1];
				return result
						.stream()
						.filter(dictBasic -> dictBasic.getGroupCode().contains(groupCode))
						.collect(Collectors.toList());
			} else {
				return result;
			}
		}

		List<DictBasic> list = new ArrayList<DictBasic>();
		for (String obj : strings) {
			DictBasic db = new DictBasic();
			db.setCode(obj.split(",")[0]);
			if (obj.split(",").length > 1) {
				db.setGroupCode(obj.split(",")[1]);
			} else {
				db.setGroupCode("");
			}
			list.add(db);
		}
		return this.mapper.selectDictBasicsWithGroup(list);
	}


	//	@Cacheable(value="selectAllDiceByCodeBuildTree",key="selectAllDiceByCodeBuildTree")
	public List<Map<String, Object>> selectAllDiceByCodeBuildTree(String code) {
		return mapper.selectAllDiceByCodeBuildTree(code);
	}

	public List<Map<String, Object>> selectByCodeAndGroupcodeBuildTree(String code) {
		if (!code.isEmpty()) {
			String[] tmpArr = code.split(",");
			String dictCode = tmpArr[0];
			String groupCode = tmpArr.length > 1 ? tmpArr[1] : "";
			return mapper.selectByCodeAndGroupcodeBuildTree(dictCode, groupCode);
		}
		return null;
	}

	//	@Cacheable(value="selectDictByCode",key="#code+'selectDictByCode'")
	public List<DictBasic> selectDictByCode(String code) {
		List<DictBasic> result;
		if (dicts.containsKey(code)) {
			result = dicts.get(code);
		} else {
			result = mapper.selectDictByCode(code);
			if (result.size() < 150) {
				dicts.put(code, result);
			}
		}
		return result;
	}


	public List<DictBasic> selectDictByDisplay(String display){
		List<DictBasic> result;
		if (dicts.containsKey(display)) {
			result = dicts.get(display);
		} else {
			result = mapper.selectDictBasicByDisplay(display);
			if (result.size() < 150) {
				dicts.put(display, result);
			}
		}
		return result;
	}

	/**
	 * 清空字典缓存
	 */
	public void flushDictCache() {
		if (dicts != null) {
			dicts.clear();
		}
	}


	/**
	 * 
	 * 方   法  名：selectDictBasicList
	 * 创建日期：2018年08月1日 下午9:18:12
	 * 创   建  者：lijing
	 * 描          述：查询字典列表
	 * @param 
	 * @return
	 */
	public List<DictBasic> selectDictBasicList(Integer num,Integer size,String code,String isUsing){
		
		PageHelper.startPage(num,size);
		List<DictBasic> list = this.mapper.selectDictBasicList(code, isUsing);
		if(list !=null && list.size() >0) {
			list.stream().forEach((d) ->{
				if(d.getPicId()!=null) {
					d.setFileUploadList(FileUploadUtil.getFileUploadList(d.getPicId()));
				}
			});
		}
		return list;
	}
	
	/**
	 * 
	 * 方   法  名：insertOrUpdateDictBasic
	 * 创建日期：2018年08月1日 下午9:18:12
	 * 创   建  者：lijing
	 * 描          述：新增或修改
	 * @param 
	 * @return
	 */
	public void insertOrUpdateDictBasic(DictBasic dictBasic) {
		
		if(dictBasic.getId() != null && !"".equals(dictBasic)) {
			
			if(dictBasic.getFileUploadList()!=null && dictBasic.getFileUploadList().size() >0) {
				dictBasic.setPicId(FileUploadUtil.saveFileUploadList(dictBasic.getFileUploadList(),""));
			}
			this.mapper.updateByPrimaryKeySelective(dictBasic);
		
			flushDictCache();
		}else {
			if(dictBasic.getFileUploadList()!=null && dictBasic.getFileUploadList().size() >0) {
				dictBasic.setPicId(FileUploadUtil.saveFileUploadList(dictBasic.getFileUploadList(),UUIDUtil.getUUID()));
			}
			dictBasic.setId(UUIDUtil.getUUID());
			this.mapper.insertSelective(dictBasic);
			flushDictCache();
		}
	}
	
	/**
	 * 
	 * 方   法  名：selectDictBasicById
	 * 创建日期：2018年08月1日 下午9:18:12
	 * 创   建  者：lijing
	 * 描          述：根据id查询
	 * @param 
	 * @return
	 */
	public DictBasic selectDictBasicById(String id) {
		if(id == null) {
			throw new BusinessException("id.is.null","id为空");
		}
		DictBasic d = this.mapper.selectByPrimaryKey(id);
		if(d != null) {
			if(d.getPicId()!=null) {
				d.setFileUploadList(FileUploadUtil.getFileUploadList(d.getPicId()));
			}
		}
		return d;
	}
	
	
	/**
	 * 
	 * 方   法  名：selectDictBasicMAXfuncValue
	 * 创建日期：2017年12月08日 下午7:59:06
	 * 创   建  者：li.jing
	 * 描          述：生成字典值
	 * @param 
	 * @return
	 */
	public String selectDictBasicMAXfuncValue(String id,String code){
			
			
			String orgCode ="";
			if(id!=null && !"".equals(id)) {
				DictBasic db = this.mapper.selectDictBasicById(id);
				DictBasic d = new DictBasic();
				if(db!=null && !"".equals(db)) {
					orgCode =db.getValue()+"";
					d.setValue(Integer.valueOf(orgCode));
				}else {
					d.setValue(0);
				}
				d.setCode(code);
	            List<DictBasic> directLevelList = this.mapper.selectDirectLevelOrgsNoSearchNotOnlyManager(d);	        		        	
        		if (directLevelList == null || (directLevelList != null && directLevelList.size() < 1)) {
                    orgCode = d.getValue() + "001";
                } else {
                	String lastOrgCode = directLevelList.get(directLevelList.size() - 1)+"";
	                	if(lastOrgCode.length() >=3) {
	                		String lastStr = lastOrgCode.substring(lastOrgCode.length() - 1);
		                    String last2Str = lastOrgCode.substring(lastOrgCode.length() - 2);
		                    String last3Str = lastOrgCode.substring(lastOrgCode.length() - 3);
		                    if (Integer.parseInt(lastStr) < 9) {
		                        orgCode = lastOrgCode.substring(0, lastOrgCode.length() - 1) + (Integer.parseInt(lastStr) + 1) + "";
		                    } else if (Integer.parseInt(last2Str) < 99) {
		                        orgCode = lastOrgCode.substring(0, lastOrgCode.length() - 2) + (Integer.parseInt(last2Str) + 1) + "";
		                    } else if (Integer.parseInt(last3Str) < 999) {
		                        orgCode = lastOrgCode.substring(0, lastOrgCode.length() - 3) + (Integer.parseInt(last3Str) + 1) + "";
		                    }
	                		
	                	}else {
	    	        		List<String> list = this.mapper.selectDictBasicMax(code);
	    	        		orgCode = Integer.valueOf(list.get(0))+1+"";
	    	        	}
                	}	
			}else {
				
				List<String> list = this.mapper.selectDictBasicMax(code);
        		if(list != null && list.size() >0) {
        			String org = list.get(0);
        			if(org != null && !"".equals(org)) {
        				if(org.length() >=3) {
	               			 if (Integer.parseInt(org) < 9) {
	       	                        orgCode = org.substring(0, org.length() - 1) + (Integer.parseInt(org) + 1) + "";
	       	                    } else if (Integer.parseInt(org) < 99) {
	       	                        orgCode = org.substring(0, org.length() - 2) + (Integer.parseInt(org) + 1) + "";
	       	                    } else if (Integer.parseInt(org) < 999) {
	       	                        orgCode = org.substring(0, org.length() - 3) + (Integer.parseInt(org) + 1) + "";
	       	                    }
		               		}else {
		               			orgCode = Integer.valueOf(org)+1+"";
		               		}
        			}else {
        				orgCode = 1+"";
        			}
            		
        		}else {
        			orgCode = 1+"";
        		}
				
        		
			}
		return orgCode;
	}

	public List<DictBasic> selectDictBasicListByCodeAndValue(String code,String value){
		List<DictBasic> dictBasics = this.mapper.selectDictBasicListByCodeAndValue(code, value);
		if(dictBasics!=null && dictBasics.size() >0) {
			List<FileUpload> fileUploadList = null;
			for (int i = 0 ; i < dictBasics.size() ; i++ ){
				if (dictBasics.get(i).getValue() == 3){
					dictBasics.remove(i);
				}
			}
			for (DictBasic basic : dictBasics) {
				if (basic.getPicId() == null) {
                    continue;
                }
				fileUploadList = FileUploadUtil.getFileUploadList(basic.getPicId());
				if(fileUploadList!=null && fileUploadList.size() >0) {
					basic.setPicUrl(fileUploadList.get(0).getUrl());
					fileUploadList=null;
				}
			}
		}
		return dictBasics;
	}

	/**
	 * @author 王海洋
	 * @methodName: getValueByCodeKey
	 * @methodDesc: 根据code和codeVal获取字典显示内容
	 * @description:
	 * @param: [code, codeKey]
	 * @return java.lang.String
	 * @create 2019-08-24 13:48
	 **/
	public String getDisplayByCodeVal(String code,String codeVal) {
		List<DictBasic> result;
		if (dicts.containsKey(code)) {
			result = dicts.get(code);
		} else {
			result = mapper.selectDictByCode(code);
			if(result!=null && result.size()>0){
				dicts.put(code, result);
			}
		}
		if(result!=null && result.size()>0){
			for(DictBasic dictBasic:result){
				if(dictBasic.getValue().toString().equals(codeVal)){
					return dictBasic.getDisplay();
				}
			}
		}
		return null;
	}
	
}